package com.winning.pmph.ctrl;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.winning.pmph.entity.Book;
import com.winning.pmph.entity.IncreaseBook;
import com.winning.pmph.service.BookService;
import com.winning.pmph.service.IncreaseBookService;
import com.winning.pmph.utils.*;
import com.winning.pmph.vo.IncreaseBookVo;
import com.winning.pmph.vo.ResultData;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lbm
 * @since 2021-12-24
 */
@Api(value = "图书增值服务")
@RestController
@RequestMapping("/pmph/action/increaseBook")
public class IncreaseBookCtrl {
	@Autowired
    private IncreaseBookService increaseBookService;
	@Autowired
	private BookService bookService;

	@ApiOperation(value = "selectGetPageList", notes = "获取增值服务图书列表接口")
	@RequestMapping("selectGetPageList")
	public Page<IncreaseBook> selectGetPageList(String searchText, Integer sourcePubType, Integer pubStatus,Integer currentPage, Integer pageSize) {
		if (currentPage == null || currentPage == 0) {
			currentPage = 1;
		}
		if (pageSize == null || pageSize == 0) {
			pageSize = 10;
		}
		String username = PMPHAppUtil.getCurrentUserEnName();
		Page<IncreaseBook> page = increaseBookService.lambdaQuery()
				.eq(!"admin".equals(username),IncreaseBook::getCreateBy,username)
				.eq(sourcePubType!=null && sourcePubType!=0, IncreaseBook::getSourcePubType, sourcePubType)
				.eq(pubStatus!=null && pubStatus!=0, IncreaseBook::getPubStatus, pubStatus)
				.ne(IncreaseBook::getPubStatus, 3)
				.and(StringUtils.isNotBlank(searchText),item->item.like( IncreaseBook::getBookName, "%"+searchText+"%")
						.or()
						.like( IncreaseBook::getIsbn, "%"+searchText+"%")
						.or()
						.like( IncreaseBook::getTopicNumber, "%"+searchText+"%"))
				.orderByDesc(IncreaseBook::getCreateTime)
				.page(new Page<>(currentPage, pageSize));
		return page;
	}
	
	@ApiOperation(value = "uploadFile", notes = "上传文件")
	@RequestMapping("uploadFile")
    public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        Map<String, Object> result = new HashMap<>();
        String path = "increasebook/";
        String savePath = ApplicationContextUtil.BASE_DOWN_FORDER + path;
        String name = UploadFileUtil.uploadFile(file, savePath, true);
        result.put("path", "/"+path+name);
        result.put("originalName", file.getOriginalFilename());
        return result;
    }
	
	@ApiOperation(value = "uploadImg", notes = "上传图片")
	@RequestMapping("uploadImg")
	public void uploadImg(@RequestParam("file") MultipartFile file,
			@RequestParam("bookId") String bookId) throws Exception {
		increaseBookService.uploadImg(file, bookId);
	}
	
	@ApiOperation(value = "add", notes = "新增图书")
	@RequestMapping("add")
    public ResultData<String> add(@RequestBody IncreaseBook increaseBook) throws Exception {
		increaseBook.setUpdateTime(new Date());
		increaseBook.setUpdateBy(PMPHAppUtil.getCurrentUserEnName());
		String topicNumber = increaseBook.getTopicNumber();
		List<IncreaseBook> list = increaseBookService.lambdaQuery().notIn(IncreaseBook::getPubStatus,3).eq(IncreaseBook::getTopicNumber, topicNumber).list();
		if(list!=null && list.size()>0) {
			return ResultData.fail("选题号重复，请重新填写");
		}
		if(StringUtils.isNotBlank(increaseBook.getId())) {
			increaseBookService.updateById(increaseBook);
		}else {
			IncreaseBookVo bookVo = new IncreaseBookVo();
			bookVo.setBookName(increaseBook.getBookName());
			bookVo.setTopicNumber(increaseBook.getTopicNumber());
			if(StringUtils.isNotBlank(increaseBook.getIsbn())) {
				bookVo.setIsbn(increaseBook.getIsbn());
			}else {
				bookVo.setIsbn(null);
			}
			bookVo.setSourcePubType(increaseBook.getSourcePubType());
			Book book = bookService.insertIncreaseBook(bookVo);
			String bookId = book.getId();
			IncreaseBook increaseBookOld = increaseBookService.getById(bookId);
			if(increaseBookOld==null) {
				increaseBook.setId(bookId);
				increaseBook.setCreateTime(new Date());
				increaseBook.setCreateBy(PMPHAppUtil.getCurrentUserEnName());
				increaseBook.setPubStatus(1);//默认未发布
				increaseBook.setQualityStatus(1);//默认未付型
				increaseBookService.save(increaseBook);
				Integer sourcePubType = increaseBook.getSourcePubType();
				//调用增值H5端接口向增实那边调权益相关接口
				if(sourcePubType!=null && sourcePubType==1) {
					increaseBookService.addIncreaseAip(increaseBook.getTopicNumber(),increaseBook.getBookName(),increaseBook.getIsbn());
				}
			}
		}
		return ResultData.success("添加成功");
    }
	
	@ApiOperation(value = "update", notes = "更新")
	@RequestMapping("update")
    public void update(@RequestBody IncreaseBook increaseBook) throws Exception {
		String bookId = increaseBook.getId();
		if(StringUtils.isBlank(increaseBook.getId())) {
			return;
		}
		increaseBook.setUpdateTime(new Date());
		increaseBook.setUpdateBy(PMPHAppUtil.getCurrentUserEnName());
		if(increaseBook.getPubStatus()!=null && increaseBook.getPubStatus()==2) {
			increaseBook.setPubTime(new Date());
			bookService.publishBook(bookId);
			bookService.syncBook(bookId, "rwzyzs_knowledge", PMPHAppUtil.getCurrentUserEnName());
		}else if(increaseBook.getPubStatus()!=null && increaseBook.getPubStatus()==3){
			bookService.deleteBookById(bookId,"increase");
			ExecutorServiceFactory.getInstance().submit(() -> {
	        	increaseBookService.syncBookData();
	        });
		}
		increaseBookService.updateById(increaseBook);
    }
	
	@ApiOperation(value = "getById", notes = "获取增值服务图书")
	@RequestMapping("getById")
    public IncreaseBook getById(String id) throws Exception {
		IncreaseBook increaseBook = increaseBookService.getById(id);
        return increaseBook;
    }
	
	@ApiOperation(value = "delete", notes = "删除增值服务图书")
	@RequestMapping("delete")
    public void delete(String id) throws Exception {
		increaseBookService.removeById(id);
		String userName = PMPHAppUtil.getCurrentUserEnName();
		bookService.deleteBookById(id,"increase");
		increaseBookService.sendDeleteBookData(id,userName);
    }
	
	@ApiOperation(value = "pushBook", notes = "推送增值服务数据")
	@GetMapping("pushBook")
    public void pushBook(Integer isAllPush) throws Exception {
		String userName = PMPHAppUtil.getCurrentUserEnName();
        ExecutorServiceFactory.getInstance().submit(() -> {
        	increaseBookService.syncBookData(userName,isAllPush);
        });
    }
	
	@ApiOperation(value = "editBookPubType", notes = "修改图书开发类型")
	@GetMapping("editBookPubType")
    public void editBookPubType(@RequestBody IncreaseBook increaseBook) throws Exception {
		String bookId = increaseBook.getId();
		if(StringUtils.isBlank(increaseBook.getId())) {
			return;
		}
		increaseBook.setUpdateTime(new Date());
		increaseBook.setUpdateBy(PMPHAppUtil.getCurrentUserEnName());
		increaseBookService.updateById(increaseBook);
		//bookService.publishBook(bookId);
    }

	public static void main(String[] args) {
		String uri = "http://192.168.107.209:5200/tszz-web/increaseBook/addIncreaseAip";
		Map<String,String> params = new HashMap<>();
		//params.put("isbn", increaseBook.getIsbn());
		params.put("topicNumber", "18283323456");
		JSONObject json = HttpApi.get(uri, params);
		System.out.println(json);
	}

}

